/**
 * 匠言知识付费v2.0.0
 * Author: 山西匠言网络科技有限公司
 * 这不是一个免费软件，它受限于许可条款，你可以访问https://www.zsfzxkc.cn/获取更多详细信息。
 * This is not a free software, it under the license terms, you can visit https://www.zsffzxkc.cn/ get more details.
 */
<template>
	<view class="container">
	        <live-pusher style="width: 100%;height: 500upx;" id='livePusher' ref="livePusher" class="livePusher" :url="url"
	        mode="SD" :beauty="beauty" :whiteness="whiteness"
	        @statechange="statechange" @netstatus="netstatus" @error = "error"
	        ></live-pusher>
	        <button class="btn" @click="startlive">开播</button>
	        <button class="btn" @click="pauselive">暂停</button>
	        <button class="btn" @click="stoplive">下播</button>
	        <button class="btn" @click="switchCamera">翻转</button>
			<button class="btn" @click="notalk">禁言</button>
			<!-- 互动 -->
			<scroll-view scroll-y="true" class="interact" @scroll="scrollChange" @scrolltolower="scrolltolower" :scroll-into-view="lastmsgid">
				<view class="interact-list" v-for="(item, index) in messageList" :key="index" >
					<view v-if="item.msg_type=='login' ">
						<view class="interact-list-left" :id="'msg'+index">
							<view class="left-info">
								<text decode>系统消息:</text>
								<view class="info-context"><text style="background-color: #eee;">欢迎{{item.nickname}}进入直播间</text></view>
							</view>
						</view>
					</view>
					<view v-else-if="item.msg_type=='xitong' ">
						<view class="interact-list-left" :id="'msg'+index">
							<view class="left-info">
								<text decode>{{item.nickname}}</text>
								<view class="info-context"><text style="background-color: #eee;">{{item.msg}}</text></view>
							</view>
						</view>
					</view>
					<view v-else>
						<!-- 自己发的消息 -->
						<view v-if="item.uid == userinfo.uid" class="interact-list-right" :id="'msg'+index">
							<view class="right-info">
								<text decode>{{item.nickname}}</text>
								<view class="info-context"><text>{{item.send_msg}}</text></view>
							</view>
							<image class="right" :src="item.avatar" mode="aspectFit"></image>
						</view>
						
						<!-- 别人发来的消息 -->
						<view v-else class="interact-list-left" :id="'msg'+index">
							<image class="left" :src="item.avatar" mode="aspectFit"></image>
							<view class="left-info">
								<text decode>{{item.nickname}}</text>
								<view class="info-context"><text>{{item.send_msg}}</text></view>
							</view>
						</view>
					</view>
				</view>
					<!-- 发送消息 -->
				<view class="send">
					<image src="/static/users.png" mode="" @click="usersshowbtn"></image>
					<input type="text" @input="changeMsg" placeholder="说点什么..." :value="sendMessage" />
					<button @click="sendMsg" type="primary">发送</button>
				</view>
				<!-- 用户列表 -->
				<scroll-view scroll-y="true" class="userlist" v-if="usersshow">
					<view class="totalnum">
						用户列表 共{{allusers.length}}人
					</view>
					<view v-for="(item,index) in allusers" :key="index">
						<view class="userinfo">
							{{item}} 在线
						</view>
					</view>
				</scroll-view>
			</scroll-view>
	    </view>
		
</template>

<script>
	import { checkUserinfo } from '@/request/checkUserinfo'
    export default {
        data() {
            return {
				url:"",
				beauty:0,
				whiteness:0,
				userinfo:{},
				id:'',
				HOST_URL:uni.HOST_URL,
				issocketOpen: false,
				sendMessage: '',
				userinfo: '',
				msg_type:'say',
				zbid:'',
				messageList: [],
				lastmsgid:'',
				allusers:[],
				usersshow:false,
				zbinfo:[]
			}
        },
		onLoad(e) {
			this.id=this.zbid=e.liveid
			checkUserinfo()
			let userinfo = uni.getStorageSync('userinfo')
			this.userinfo = userinfo;
			this.getcourse(e.liveid);
			// this.context = uni.createLivePusherContext("livePusher", this);
		},
		onShow() {
			//获取聊天内容
			this.connectSocketInit();
		},
		onUnload() {
			uni.closeSocket()
		},
        onReady(e) {
			this.context = uni.createLivePusherContext("livePusher", this);
        },
        methods: {
			usersshowclose(){
				this.usersshow=false
			},
			usersshowbtn(){
				this.usersshow=this.usersshow==true?false:true
			},
			// 点击发送消息
			sendMsg(e) {
				var data = {
						uid: this.userinfo.uid,
						msg_type:this.msg_type,
						nickname: this.userinfo.userdata.nickname,
						avatar: encodeURIComponent(this.userinfo.userdata.avatar),
						live_type: 'course',
						zbid: this.zbid
					}
				if(e=='login'){
					if(this.issocketOpen) {
						data.msg_type='login'
						uni.sendSocketMessage({
							data: JSON.stringify(data),
							success: res => {
								console.log(res)
							}
						})
					}
				}else{
					if(this.msg_type=='say'){
						if(this.sendMessage==''){
							uni.showToast({
								title:'发送内容不能为空',
								icon:'none'
							})
							return false
						}else{
							data.send_msg=this.sendMessage
							if(this.issocketOpen) {
								uni.sendSocketMessage({
									data: JSON.stringify(data),
									success: res => {
										this.sendMessage=''
									}
								})
							}
						}
					}
				}
			},
			scrolltolower(){
				this.lastmsgid='msg'+(this.messageList.length-1)
			},
			scrollChange(e) {
				this.lastmsgid=''
			},
			changeMsg(e){
				this.sendMessage=e.detail.value
			},
			//获取直播信息
			getcourse(id){
				const BASE_URL = uni.BASE_URL
				uni.request({
					url: BASE_URL + 'index/live/getliveinfo',
					method: 'post',
					data:{
						id:id
					},
					success: (res) => {
						if(res.data.code == 0){
							this.zbinfo=res.data.data;
							this.url = res.data.data.tlurl;
							this.beauty = res.data.data.beauty;
							this.whiteness = res.data.data.whiteness;
							console.log(res.data.data.tlurl)
						}else{
							console.log(res.data);
						}
					},
					fail: (res) => {
						console.log(res.data);
					}
				});
			},
			
			// 创建websocket链接
			connectSocketInit() {
				const WSS_URL = uni.WSS_URL
				uni.connectSocket({
					url: WSS_URL
				})
				uni.onSocketOpen(res => {
					this.issocketOpen = true
				  console.log('WebSocket连接已打开！', res);
					this.sendMsg('login')
				})
				uni.onSocketMessage(res => {
				    console.log('收到服务器内容：' + res.data);
					let msgList = JSON.parse(res.data)
					msgList.avatar = decodeURIComponent(msgList.avatar)
					if(msgList.msg_type === 'say') this.messageList.push(msgList)
					this.lastmsgid='msg'+(this.messageList.length-1)
					if(msgList.msg_type === 'login') {
						this.messageList.push(msgList)
						this.lastmsgid='msg'+(this.messageList.length-1)
						if(msgList.uid==this.userinfo.uid){
							var xitongmsg={
								'msg_type':'xitong',
								'msg':'请您文明发言，严禁发布涉政、黄赌毒等违法信息',
								'nickname':'系统消息:'
							}
							this.messageList.push(xitongmsg)
							this.lastmsgid='msg'+(this.messageList.length-1)
						}
					}
					if(msgList.type === 'logout') {
						var user =[]
						if(msgList.client_list){
							for(const key in msgList.client_list){
								// console.log(msgList.client_list[key])
							   user.push(msgList.client_list[key])
							}
							this.allusers=user
						}
						var xitongmsg={
							'msg_type':'xitong',
							'msg':msgList.from_client_name+'离开了直播间',
							'nickname':'系统消息:'
						}
						this.messageList.push(xitongmsg)
						this.lastmsgid='msg'+(this.messageList.length-1)
					}
					if(msgList.msg_type === 'ping') {
						uni.sendSocketMessage({
							data: '{"msg_type":"pong"}'
						})
					}
					if(msgList.type === 'login') {
						var user =[]
						for(const key in msgList.client_list){
							// console.log(msgList.client_list[key])
						   user.push(msgList.client_list[key])
						}
						this.allusers=user
					}
				});
				uni.onSocketError(res => {
				  console.log('WebSocket连接打开失败，请检查！');
				});
				
			},
			
            statechange(e) {
                console.log("statechange:" + JSON.stringify(e));
            },
            netstatus(e) {
                console.log("netstatus:" + JSON.stringify(e));
            },
            error(e) {
                console.log("error:" + JSON.stringify(e));
            },
            startlive(){
				console.log('ok11')
                this.context.start({
                    success: (a) => {
                        console.log("livePusher.start:" + JSON.stringify(a));
						const BASE_URL = uni.BASE_URL
						uni.request({
							url: BASE_URL + 'index/live/changelivestate',
							method: 'post',
							data:{
								id:this.zbid,
								state:this.zbinfo.is_jy==0?1:0
							},
							success: (res) => {
								console.log(res.data);
								uni.showToast({
									title:res.data.msg
								})
							},
							fail: (res) => {
								console.log(res.data);
							}
						});
                    }
                });

            },
			notalk(){
				const BASE_URL = uni.BASE_URL
				uni.request({
					url: BASE_URL + 'index/live/changelivestate',
					method: 'post',
					data:{
						id:this.zbid,
						is_jy:1
					},
					success: (res) => {
						console.log(res.data);
						uni.showToast({
							title:res.data.msg
						})
					},
					fail: (res) => {
						console.log(res.data);
					}
				});
			},
            closelive () {
                this.context.close({
                    success: (a) => {
                        console.log("livePusher.close:" + JSON.stringify(a));

                    }
                });
            },
            snapshot: function() {
                this.context.snapshot({
                    success: (e) => {
                        console.log(JSON.stringify(e));
                    }
                });
            },
            resumelive () {
                this.context.resume({
                    success: (a) => {
                        console.log("livePusher.resume:" + JSON.stringify(a));
                    }
                });
            },
            pauselive () {
                this.context.pause({
                    success: (a) => {
                        console.log("livePusher.pause:" + JSON.stringify(a));
                    }
                });
            },
            stoplive () {
                this.context.stop({
                    success: (a) => {
                        console.log(JSON.stringify(a));
						const BASE_URL = uni.BASE_URL
						uni.request({
							url: BASE_URL + 'index/live/changelivestate',
							method: 'post',
							data:{
								id:this.zbid,
								state:3
							},
							success: (res) => {
								console.log(res.data);
								uni.showToast({
									title:res.data.msg
								})
							},
							fail: (res) => {
								console.log(res.data);
							}
						});
                    }
                });
            },
            switchCamera: function() {
                this.context.switchCamera({
                    success: (a) => {
                        console.log("livePusher.switchCamera:" + JSON.stringify(a));
                    }
                });
            },
            startPreview: function() {
                this.context.startPreview({
                    success: (a) => {
                        console.log("livePusher.startPreview:" + JSON.stringify(a));
                    }
                });
            },
            stopPreview: function() {
                this.context.stopPreview({
                    success: (a) => {
                        console.log("livePusher.stopPreview:" + JSON.stringify(a));
                    }
                });
            }
        }
    }
</script>
<style lang="less" scoped>
	.container{
		height: 100vh;
		width: 100%;
	}
	button{
		width: 20%;
		float: left;
	}
	.userlist{
		border-radius: 8rpx;
		width: 50%;
		height: calc(100vh - 580upx);
		background-color: #8bc34a;
		position: fixed;
		padding: 0 10upx;
		left:0;
		bottom:80rpx;
		color: #333;
		.totalnum{
			margin:15rpx 0;
			font-size: 32rpx;
		}
		.userinfo{
			padding: 5rpx;
			border-bottom: 1rpx solid #eee;
		}
	}
		// 互动
		.interact {
			height: calc(100vh - 700upx);
			padding: 10upx 20upx;
			box-sizing: border-box;
			margin-top: 100upx;
			
			&-list {
				margin-bottom: 10upx;
				&-left {
					display: flex;
					.left {
						width: 70upx;
						height: 70upx;
						border-radius: 50%;
					}
					.left-info {
						margin-left: 20upx;
						text {
							font-size: 28upx;
							color: #a4a6a6;
						}
						.info-context {
							margin-top: 10upx;
							text {
								display: block;
								max-width: 480upx;
								font-size: 28upx;
								color: #333;
								background-color: #a5ec72;
								padding: 4upx 10upx;
								border-radius: 5upx;
							}
						}
					}
				}
				&-right {
					display: flex;
					justify-content: flex-end;
					.right-info {
							text-align: right;
							margin-right: 20upx;
							margin-top: 10upx;
							text {
								font-size: 28upx;
								color: #a4a6a6;
								position: relative;
								right: 0;
							}
							.info-context {
								margin-top: 10upx;
								text {
									display: block;
									max-width: 480upx;
									font-size: 28upx;
									color: #333;
									text-align: left;
									background-color: #e8e8e8;
									padding: 4upx 10upx;
									border-radius: 5upx;
								}
							}
						}
						.right {
							width: 70upx;
							height: 70upx;
							border-radius: 50%;
						}
					}
				}
				
			.send {
				width: 750upx;
				height: 80upx;
				box-sizing: border-box;
				border-top: 2upx solid #ddd;
				background-color: #fff;
				display: flex;
				justify-content: space-around;
				align-items: center;
				position: fixed;
				left: 0;
				bottom: 0;
				image{
					width: 50upx;
					height: 50upx;
					margin: 0 20upx;
				}
				input {
					padding: 0 5upx;
					border: 2upx solid #ddd;
					width: 400upx;
					height: 50upx;
					border-radius: 10upx;
				}
				button {
					height: 55upx;
					background-color: #07b35d;
					line-height: 55upx;
					font-size: 30upx;
					color: #fff;
					letter-spacing: 6upx;
				}
			}
		}
	
</style>